import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:interview/components/app/app_confirm_dialog.dart';
import 'package:interview/components/app/app_ripple_button.dart';
import 'package:interview/theme/app_colors.dart';
import 'package:interview/controller/search_history_controller.dart';

/* 
SearchHistoryController 最优的方式是被外部传入 共用一个 controller 

其实 controller 一般不要被 static 修饰
static 修饰会发生什么
1. 将变量或方法绑定到类本身，而不是绑定到类的实例。也就是说，static 成员在所有类的实例之间是 共享的，并且它们只会在类加载时被初始化一次。
2. 在组件中，如果 SearchHistoryController 被 static 修饰，那么它会变成所有 SearchHistory 实例的共享成员 ，不会随着实例的创建和销毁而重新初始化，会导致内存泄漏，static 会导致所有用户共享同一个搜索历史状态。

static 是共享的，const 是不可变的。
所以在SearchHistory 中要去掉 const 因为每个 controller 都是独特的

 */
class SearchHistory extends StatefulWidget {
  final AppColors theme;
  final Function(String historyKeyword) onHistoryKeywordTap;
  final SearchHistoryController searchHistoryController;

  SearchHistory({
    super.key,
    required this.onHistoryKeywordTap,
    required this.theme,
    required this.searchHistoryController,
  });

  @override
  _SearchHistoryState createState() => _SearchHistoryState();
}

class _SearchHistoryState extends State<SearchHistory> {
  final GlobalKey<AnimatedListState> _listKey = GlobalKey<AnimatedListState>();
  late List<String> _history;

  @override
  void initState() {
    super.initState();
    _history = List.from(widget.searchHistoryController.searchHistory);
  }

  // 清除全部历史记录
  Future<void> _clearAll(BuildContext context) async {
    bool? confirmed = await AppConfirmDialog.show(
      context: context,
      theme: widget.theme,
      content: Center(
        child: Text(
          "历史搜索记录清除后无法恢复，确定清除全部记录吗？",
          style: TextStyle(
            fontSize: 12,
            fontWeight: FontWeight.w500,
            color: widget.theme.contrastMix3,
          ),
        ),
      ),
      confirmText: "清除",
      cancelText: "取消",
    );

    if (confirmed == true) {
      for (int i = _history.length - 1; i >= 0; i--) {
        _removeItem(i, animated: true);
      }
      widget.searchHistoryController.clearSearchHistory();
    }
  }

  // 删除单个记录
  void _removeItem(int index, {bool animated = false}) {
    final removedItem = _history[index];

    if (animated) {
      // 触发移除动画
      _listKey.currentState?.removeItem(
        index,
        (context, animation) => _buildItem(removedItem, index, animation: animation, isRemoving: true),
        duration: Duration(milliseconds: 300),
      );
    }
    _history.removeAt(index);
    widget.searchHistoryController.removeSearchKeyword(removedItem);

  }

  Widget _buildItem(String keyword, int index, {Animation<double>? animation, bool isRemoving = false}) {
    final theme = widget.theme;

    // 定义水平位移动画
    final slideAnimation = animation?.drive(
      Tween<Offset>(
        begin: isRemoving ? Offset(1, 0) : Offset(0, 0), // 仅在移除时右滑出屏幕
        end: Offset(0, 0), // 保持当前位置
      ).chain(CurveTween(curve: Curves.easeOut)), // 添加动画曲线
    );

    return SlideTransition(
      position: slideAnimation ?? AlwaysStoppedAnimation(Offset(0, 0)), // 默认保持原位置
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 6),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(
              child: AppRippleButton(
                onTap: isRemoving ? null: () {widget.onHistoryKeywordTap(keyword); },
                padding: const EdgeInsets.only(top: 4, bottom: 4),
                backgroundColor: theme.subjectPure!,
                splashColor: theme.contrastMix3!.withOpacity(0.2),
                highlightColor: theme.subjectMix1!.withOpacity(0.1),
                child: Row(
                  children: [
                    Icon(
                      Icons.access_alarms,
                      size: 14,
                      color: theme.contrastMix3,
                    ),
                    const SizedBox(width: 12),
                    Text(
                      keyword,
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w500,
                        color: theme.contrastMix3,
                      ),
                    ),
                  ],
                ),
              ),
            ),
            AppRippleButton(
              onTap: isRemoving? null : () { _removeItem(index, animated: true);},
              padding: const EdgeInsets.all(2),
              rippleRadius: BorderRadius.circular(8),
              borderRadius: BorderRadius.circular(8),
              child: Icon(
                Icons.close,
                size: 12,
                color: theme.contrastMix3,
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final theme = widget.theme;

    return Obx(() {
      final history = widget.searchHistoryController.searchHistory;

      if (history.isEmpty) {
        return const SizedBox.shrink(); // 无历史记录时显示空视图
      }

      return Container(
        padding: const EdgeInsets.only(top: 12),
        width: double.infinity,
        child: Column(
          children: [
            Padding(
              padding: EdgeInsets.symmetric(vertical: 6),
              child:  Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    "搜索记录",
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.bold,
                      color: theme.contrastMix3,
                    ),
                  ),
                  const SizedBox(width: 24),
                  AppRippleButton(
                    onTap: () => _clearAll(context),
                    padding: const EdgeInsets.all(3),
                    rippleRadius: BorderRadius.circular(8),
                    borderRadius: BorderRadius.circular(8),
                    backgroundColor: theme.subjectPure!,
                    splashColor: theme.contrastMix3!.withOpacity(0.2),
                    highlightColor: theme.subjectMix1!.withOpacity(0.1),
                    child: Icon(
                      CupertinoIcons.delete,
                      size: 16,
                      color: theme.contrastMix3,
                    ),
                  ),
                ],
              ),
            ),
            Expanded(child: 
              AnimatedList(
                key: _listKey,
                initialItemCount: _history.length,
                itemBuilder: (context, index, animation) {
                  final k = _history[index];
                  return _buildItem(k, index, animation: animation);
                },
              ),
            ),
          ],
        ),
      );
    });
  }
}